<?php

function MemberKeys ($a, $b) {
    return $a['MemberKeys'] < $b['MemberKeys'];
}

function getWhatpulseTeamData ($teamID) {
    $remote = wp_remote_get (
        'http://whatpulse.org/api/team.php?TeamID=' . (int) $teamID
    );
    $retval = array ();
    if (!is_wp_error ($result)) {
        $xml = simplexml_load_string ($remote['body']);
	if ($xml) {
	    $retval['Statistics'] = (array) $xml->TeamStats->Statistics;
	    $members = array ();
	    if (!empty ($xml->TeamStats->Members->Member)) {
		foreach ($xml->TeamStats->Members->Member as $member) {
		    $members[] = (array) $member;
		}
		usort ($members, 'MemberKeys');
		if (count ($members) > 10) 
		    $members = array_slice ($members, 0, 10); 
	    }
	    $retval['Members'] = $members;
	}
    }
    return $retval;
}

function my_whatpulse ($atts) {
    extract (
        shortcode_atts (
            array (
                'TeamID' => 17040,
            ),
            $atts
        )
    );
    $transient = 'WhatpulseTeamData_' . (int) $TeamID;
    if (false === ($wptd = get_transient ($transient))) {
        $wptd = getWhatpulseTeamData ($TeamID);
	if (!empty ($wptd)) set_transient ($transient, $wptd, 3600);
    }
    $retval = '';
    if (!empty ($wptd)) {
	extract ($wptd['Statistics']);
	$retval = sprintf (
	    '<p style="text-align:justify">Das Team <strong>%s</strong>, das ' .
	    'sich mit &quot;%s&quot; beschreibt, hat <em>%s</em> Mitglieder, ' .
	    'die insgesamt <em>%d</em> Tastenanschläge, <em>%d</em> Klicks ' .
	    'und <em>%d</em> Meilen mit der Maus gepulst haben und sich ' .
	    'damit auf Platz <em>%d</em> der Teamwertung befinden ' .
	    '(Stand %s). </p><p><em>Das Team wurde am %s von %s ' .
	    'gegründet.</em></p>',
	    $TeamName, $TeamDescription, $TeamMembers, $TeamKeys, $TeamClicks,
	    $TeamMiles, $TeamRank,
	    date ('d.m.Y G.i \U\h\r', strtotime ($GeneratedTime)),
	    date ('d.m.Y', strtotime (str_replace (' at ', ' ', $TeamDateFormed))),
	    $TeamFounder
	);
	if (!empty ($wptd['Members'])) {
	    $retval .=
		'<p><strong>Top 10 der Gruppe</strong></p><table><tr><th>' .
		'Name</th><th>Tastenanschläge</th><th>Klicks</th><th>Meilen' .
		'</th><th>Letzter Pulse</th></tr>';
	    foreach ($wptd['Members'] as $member) {
		$retval .= sprintf (
		    '<tr><td><a href="http://whatpulse.org/stats/users/%s">%s' .
		    '</a></td><td>%d</td><td>%d</td><td>%d</td><td>%s</td>' .
		    '</tr>',
		    $member['MemberUserID'], $member['MemberName'],
		    $member['MemberKeys'], $member['MemberClicks'],
		    $member['MemberMiles'],
		    date ('d.m.Y G.i \U\h\r', strtotime ($member['MemberLastPulse']))
		);
	    }
	    $retval .=
		'</table>';
	}
    }
    return $retval;
}
add_shortcode ('whatpulse', 'my_whatpulse');

?>
